package com.hedd.shop.controller;


import cn.dsna.util.images.ValidateCode;
import com.hedd.shop.constants.Constants;
import com.hedd.shop.exceptions.ShopException;
import com.hedd.shop.pojo.entity.User;
import com.hedd.shop.pojo.qo.UserLoginQO;
import com.hedd.shop.pojo.vo.RespResult;
import com.hedd.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/user")
@Api(tags = "用户业务接口")
public class UserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public RespResult login(@RequestBody UserLoginQO qo, HttpServletRequest request) {

        String code = (String)request.getSession().getAttribute("code");
        if (!qo.getCode().equalsIgnoreCase(code)) {
            throw new ShopException("验证码错误");
        }

        logger.info("login qo:{}", qo);
        User dbUser = userService.login(qo);
        //验证登录成功，用户信息存到session
        request.getSession().setAttribute(Constants.SESSION_KEY_LOGIN_USER, dbUser);
        return returnRespWithSuccess(dbUser);
    }


    @RequestMapping("/register")
    @ApiOperation("用户注册")
    public RespResult register(@RequestBody User user){
        System.out.println(user);
        int dbUser = userService.insertUser(user);
        return returnRespWithSuccess(dbUser);
    }



    @RequestMapping(value = "/getcode", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void getcode(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        ValidateCode vc =  new ValidateCode(150,40,4,10);
        String code=vc.getCode();
        HttpSession session = req.getSession();
        session.setAttribute("code", code);
        ServletOutputStream outputStream = resp.getOutputStream();
        vc.write(outputStream);
        outputStream.flush();

    }
}
